<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/3/29
 * Time: 17:05
 */

namespace App\Http\Controllers\VipChannel\Withdraw;

use App\Http\Controllers\Manage\DailyReport\Transformers\WithdrawTransformer;
use App\Http\Controllers\VipChannel\BaseController;
use App\Http\Controllers\VipChannel\Withdraw\Transformers\FinancialStatTransformer;
use App\Modules\Channel\Models\ChannelUser;
use App\Modules\Finance\Models\CashAccount;
use App\Modules\Finance\Models\FinancialStat;
use App\Modules\Finance\Services\CashAccountService;
use App\Modules\Finance\Services\FinancialConfigService;
use App\Modules\Finance\Services\FinancialPayMerchantBalanceService;
use App\Modules\Finance\Services\FinancialStatService;
use App\Modules\Finance\Services\WithdrawCashService;
use App\Modules\Trade\Models\OrderStat;
use App\Modules\Withdraw\Services\WithdrawServices;
use DB;
use Illuminate\Http\Request;

class WithdrawController extends BaseController
{
    /**
     * 获取可提现的站点的信息
     * @param Request $request
     * @return mixed
     */
    public function getFinancialStatList(Request $request)
    {
        $distribution_channel_ids = $this->getDistributionChannelIds($request);
        if (count($distribution_channel_ids) <= 0) {
            return response()->error('NOT_EXIST');
        }
        $result = FinancialStat::getFinancialStatInfo(compact('distribution_channel_ids'), false);
        foreach ($result as $item) {
            $item->account_name = '';
            $item->account_bank = '';
            $item->distribution_channel_id = $item->distribution_channel_id . '(' . $item->site_nick_name . ')';
            $distribution_channel_id = $item->distribution_channel_id;
            $orderStat = OrderStat::getRechargeAmount(explode(',', $distribution_channel_id));
            if ($orderStat) {
                $item->total_charge_amount = $orderStat->total_recharge_amount_sum;
            } else {
                $item->total_charge_amount = 0;
            }

            $account = CashAccount::getByDistributionChannel($distribution_channel_id);
            if ($account) {
                $item->account_name = $account->account_name;
                $item->account_bank = $account->account_bank;
            }
        }
        return response()->pagination(new FinancialStatTransformer(), $result);
    }

    /**
     * 获取提现列表
     * @param Request $request
     * @return mixed
     */
    public function getWithdrawList(Request $request)
    {
        $status = $request->has('status') ? $request->input('status') : '';
        $end_date = $request->has('end_date') ? $request->input('end_date') : '';
        $start_date = $request->has('start_date') ? $request->input('start_date') : '';
        $phone = $request->has('phone') ? $request->input('phone') : '';
        $channel_user_id = $request->has('channel_user_id') ? $request->input('channel_user_id') : '';
        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

        $all_channels = $this->getDistributionChannelIds($request);

        if ($channel_user_id) {
            $all_channels = ChannelUser::getChannelIdArray($channel_user_id);
        }

        if ($distribution_channel_id) {
            $all_channels = explode(',', $distribution_channel_id);
        }

        if (count($all_channels) <= 0) {
            return response()->error('NOT_EXIST');
        } else {
            $res = WithdrawServices::getVipWithdrawCashList(compact('all_channels', 'start_date', 'phone', 'end_date', 'status'));
            foreach ($res as $item) {
                $item->distribution_channel_id = $item->distribution_channel_id . '(' . $item->site_nick_name . ')';
            }
            return response()->pagination(new WithdrawTransformer(), $res);
        }
    }

    /**
     * @param Request $request
     * @return mixed
     */
    function add_withdrawCash(Request $request)
    {
        $amount = $request->has('amount') ? $request->input('amount') : '';
        $distribution_channel_id = $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';;

        if (!$distribution_channel_id || !$amount) {
            return response()->error("PARAM_EMPTY");
        }

        if (!is_numeric($amount)) {
            return response()->error("PARAM_ERROR");
        }

        if ($amount < 100) {
            //TODO 渠道14，取消100 金额的判断 大于1一块钱就可以
            if ($distribution_channel_id == 14 || $distribution_channel_id = "14" || $distribution_channel_id = '14') {
                if ($amount < 1) {
                    return response()->error("WITHDRAW_CASH_AMOUNT");
                }
            } else {
                return response()->error("WITHDRAW_CASH_AMOUNT");
            }
        }
        if ($amount >= (20 * 10000)) {
            //TODO 取消单笔提现额度限制
            //return response()->error("WITHDRAW_CASH_AMOUNT_MORE");
        }

        $remark = $request->has('remark') ? $request->input('remark') : '';
        $financialStat = FinancialStatService::getFinancialStatSingle($distribution_channel_id);
        if (empty($financialStat) || $financialStat['enable_withdrawal_amount'] < $amount) {
            //可提现金额不够
            return response()->error("WITHDRAW_CASH_AMOUNT_INSUFFICIEN");
        }

        if (FinancialConfigService::isFrozenDistributionChannel($distribution_channel_id)) {
            //渠道被冻结
            return response()->error("WITHDRAW_CASH_AMOUNT_FROZEN");
        }

        //判断账户是否设置
        if (!CashAccountService::isCashAccountExits($distribution_channel_id)) {
            return response()->error("WITHDRAW_CASH_AMOUNT_ACCOUNT");
        }

        //判断今天是否已经提现
        if (WithdrawCashService::isWithdrawCashChannelToToday($distribution_channel_id)) {
            return response()->error("WITHDRAW_CASH_TODAY_USE");
        }

        $is_company = 0;
        $cashAccount = CashAccountService::getCashAccountSingle($distribution_channel_id);
        if (!empty($cashAccount)) {
            $is_company = $cashAccount['is_company'];
        }

        $enable_by_companys = FinancialPayMerchantBalanceService::getChannelEnableWithdrawByCompanyId($distribution_channel_id);
        DB::beginTransaction();
        try {
            foreach ($enable_by_companys as $enable_by_company) {
                $with_draw_amount = ($enable_by_company->enable_withdrawal_amount >= $amount) ? $amount : $enable_by_company->enable_withdrawal_amount;
                $pay_company_id = $enable_by_company->pay_merchant_company_id;
                WithdrawCashService::addWithdrawCash($distribution_channel_id, $with_draw_amount, $remark, $pay_company_id);

                $financialStatUp = FinancialStatService::updateFinancialStatByWithdraw($distribution_channel_id, $with_draw_amount);
                FinancialPayMerchantBalanceService::updateBalanceByWithdraw($with_draw_amount, $distribution_channel_id, $pay_company_id);
                $amount = $amount - $with_draw_amount;
                //部分通道公司只能对公打款
                $pay_company_info = DB::table('pay_companies')->where('id', $pay_company_id)->first();
                if ($pay_company_info) {
                    if ($is_company == 0 && $pay_company_info->only_public_account == 1) {    //in_array($pay_company_id,explode(',',env('ZW_COMPANY_IDS')))
                        DB::rollBack();
                        return response()->error('NOT_ALLOWED_PRIVATE_ACCOUNT');
                    }
                }
                if ($amount <= 0) {
                    break;
                }
            }
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('withdraw error !' . ($e->getMessage()));
            return response()->error('WITHDRAW_CASHES_FAILED');
        }
        DB::commit();
        //修改可提现总额
        $enable_amount = $financialStatUp['enable_withdrawal_amount'];
        //修改提现中金额
        $withdraw_pending_amount = $financialStatUp['withdraw_pending_amount'];
        return response()->success(compact('enable_amount', 'withdraw_pending_amount'));
    }

    /**
     * 一键提现
     * @param Request $request
     */
    function add_all_channels_withdrawCash(Request $request)
    {
        $fail_info = [];
        $success_site = [];
        $total_withdraw_amount = 0;
        $distribution_channel_ids = $this->getDistributionChannelIds($request);
        if (count($distribution_channel_ids) < 1) {
            return response()->error('NOT_EXIST');
        }
        $result = FinancialStat::getFinancialStatInfo(compact('distribution_channel_ids'), true);
        foreach ($result as $item) {
            $enable = true;
            $amount = $item->enable_withdrawal_amount;
            $distribution_channel_id = $item->distribution_channel_id;

            if ($amount < 100) {
                array_push($fail_info, ['msg' => '账户余额小于100', 'site' => $distribution_channel_id]);
                $enable = false;
            }

            $financialStat = FinancialStatService::getFinancialStatSingle($distribution_channel_id);
            if (empty($financialStat) || $financialStat['enable_withdrawal_amount'] < $amount) {
                //可提现金额不够
                $enable = false;
                array_push($fail_info, ['msg' => '可提现金额不够', 'site' => $distribution_channel_id]);
            }

            if (FinancialConfigService::isFrozenDistributionChannel($distribution_channel_id)) {
                //渠道被冻结
                $enable = false;
                array_push($fail_info, ['msg' => '渠道被冻结', 'site' => $distribution_channel_id]);
            }

            //判断账户是否设置
            if (!CashAccountService::isCashAccountExits($distribution_channel_id)) {
                $enable = false;
                array_push($fail_info, ['msg' => '账户没设置', 'site' => $distribution_channel_id]);
            }

            //判断今天是否已经提现
            if (WithdrawCashService::isWithdrawCashChannelToToday($distribution_channel_id)) {
                $enable = false;
                array_push($fail_info, ['msg' => '今天已经提现过了', 'site' => $distribution_channel_id]);
            }

            if ($enable) {
                $is_company = 0;
                $cashAccount = CashAccountService::getCashAccountSingle($distribution_channel_id);
                if (!empty($cashAccount)) {
                    $is_company = $cashAccount['is_company'];
                }
                $orderBy = 'asc';

                $enable_by_companys = FinancialPayMerchantBalanceService::getChannelEnableWithdrawByCompanyId($distribution_channel_id, $orderBy);
                foreach ($enable_by_companys as $enable_by_company) {
                    try {
                        DB::beginTransaction();
                        $with_draw_amount = ($enable_by_company->enable_withdrawal_amount >= $amount) ? $amount : $enable_by_company->enable_withdrawal_amount;
                        $pay_company_id = $enable_by_company->pay_merchant_company_id;
                        if($with_draw_amount>0) {
                            WithdrawCashService::addWithdrawCash($distribution_channel_id, $with_draw_amount, '', $pay_company_id,1);
                            FinancialStatService::updateFinancialStatByWithdraw($distribution_channel_id, $with_draw_amount);
                            FinancialPayMerchantBalanceService::updateBalanceByWithdraw($with_draw_amount, $distribution_channel_id, $pay_company_id);
                        }

                        //部分通道公司只能对公打款
                        //部分通道公司只能对公打款
                        $pay_company_info = DB::table('pay_companies')->where('id', $pay_company_id)->first();
                        if ($pay_company_info) {
                            if ($is_company == 0 && $pay_company_info->only_public_account == 1) {    //in_array($pay_company_id,explode(',',env('ZW_COMPANY_IDS')))
                                DB::rollBack();
                            } else {
                                if ($amount > 0) {
                                    $amount = $amount - $with_draw_amount;
                                    $total_withdraw_amount += $with_draw_amount;
                                    array_push($success_site, $distribution_channel_id);
                                }
                                DB::commit();
                            }
                        } else {
                            if ($amount > 0) {
                                $amount = $amount - $with_draw_amount;
                                $total_withdraw_amount += $with_draw_amount;
                                array_push($success_site, $distribution_channel_id);
                            }
                            DB::commit();
                        }
                    } catch (\Exception $e) {
                        DB::rollBack();
                        \Log::error('withdraw error !' . ($e->getMessage()));
                    }
                }
            }
        }
        if ($total_withdraw_amount > 0) {
            return response()->success(compact('total_withdraw_amount', 'success_site', 'fail_info'));
        } else {
            \Log::error('withdraw_failed:' . $total_withdraw_amount);
            return response()->error('WITHDRAW_CASHES_FAILED');
        }
    }

    function get_all_channels_withdrawCash_confirm_info(Request $request)
    {
        $distribution_channel_ids = $this->getDistributionChannelIds($request);
        if (count($distribution_channel_ids) <= 0) {
            return response()->error('NOT_EXIST');
        }
        $result = FinancialStat::getFinancialStatInfo(compact('distribution_channel_ids'), true);

        $enableSite = [];
        $disableSeason = [
            ['msg' => '余额小于100', 'site' => []],
            ['msg' => '可提现金额不足', 'site' => []],
            ['msg' => '渠道被冻结', 'site' => []],
            ['msg' => '未设置提现账号', 'site' => []],
            ['msg' => '今日已提现', 'site' => []]
        ];
        $enable_withdrawCash_amount = 0;
        $enable_withdrawCash_site_count = 0;
        foreach ($result as $item) {
            $enable = true;
            $amount = $item->enable_withdrawal_amount;
            $distribution_channel_id = $item->distribution_channel_id;

            if ($amount < 100) {
                $disableSeason[0]['site'][] = $distribution_channel_id;
                $enable = false;
            }

            $financialStat = FinancialStatService::getFinancialStatSingle($distribution_channel_id);
            if (empty($financialStat) || $financialStat['enable_withdrawal_amount'] < $amount) {
                //可提现金额不够
                $disableSeason[1]['site'][] = $distribution_channel_id;
                $enable = false;
            }

            if (FinancialConfigService::isFrozenDistributionChannel($distribution_channel_id)) {
                //渠道被冻结
                $disableSeason[2]['site'][] = $distribution_channel_id;
                $enable = false;
            }

            //判断账户是否设置
            if (!CashAccountService::isCashAccountExits($distribution_channel_id)) {
                $disableSeason[3]['site'][] = $distribution_channel_id;
                $enable = false;
            }

            //判断今天是否已经提现
            if (WithdrawCashService::isWithdrawCashChannelToToday($distribution_channel_id)) {
                $disableSeason[4]['site'][] = $distribution_channel_id;
                $enable = false;
            }

            if ($enable) {
                $enable_withdrawCash_site_count++;
                $enable_withdrawCash_amount += $amount;
                array_push($enableSite, $distribution_channel_id);
            }
        }
        return response()->success(compact('enableSite', 'enable_withdrawCash_amount', 'enable_withdrawCash_site_count', 'disableSeason'));
    }
}